<template>
  <div class="plan-add-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>生产计划</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><EditPen /></el-icon>
          <span>{{ isEditMode ? "编辑计划" : "新增计划" }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="form-card" shadow="never" v-loading="formState.loading">
      <div class="form-header">
        <div>
          <h2>{{ formState.pageTitle }}</h2>
          <p>填写计划基础信息、选择成品后自动带出BOM组成，保存后即可在列表中查看。</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="formState.submitting" @click="handleSubmit">保存</el-button>
        </div>
      </div>

      <el-form ref="planFormRef" :model="planForm" :rules="planFormRules" label-width="100px" class="plan-form">
        <section class="section-block">
          <div class="section-header">
            <span>基础信息</span>
            <div class="code-switch">
              <span>系统编号</span>
              <el-switch v-model="formState.autoCode" :disabled="isEditMode" @change="handleAutoCodeChange" />
            </div>
          </div>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="计划编号" prop="planCode">
                <el-input v-model="planForm.planCode" placeholder="请输入计划编号" :disabled="formState.autoCode || isEditMode" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划名称" prop="planName">
                <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来源类型" prop="sourceType">
                <el-select v-model="planForm.sourceType" placeholder="请选择来源类型" class="w-100">
                  <el-option v-for="item in sourceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成品名称" prop="productName">
                <el-input v-model="planForm.productName" placeholder="请选择成品" readonly>
                  <template #suffix>
                    <el-icon class="clickable-icon" @click="openProductSelector"><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成品编号">
                <el-input v-model="planForm.productId" placeholder="自动带出" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格型号">
                <el-input v-model="planForm.productmodelsame" placeholder="自动带出" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位">
                <el-input v-model="planForm.productunit" placeholder="自动带出" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成品类型">
                <el-input :model-value="planForm.producttypeid ?? ''" placeholder="自动带出" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划数量" prop="planCount">
                <el-input-number v-model="planForm.planCount" :min="0" class="w-100" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开工日期" prop="planStartTime">
                <el-date-picker
                  v-model="planForm.planStartTime"
                  type="date"
                  placeholder="请选择开工日期"
                  value-format="YYYY-MM-DD"
                  class="w-100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完工日期" prop="planEndTime">
                <el-date-picker
                  v-model="planForm.planEndTime"
                  type="date"
                  placeholder="请选择完工日期"
                  value-format="YYYY-MM-DD"
                  class="w-100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需求日期" prop="demandDate">
                <el-date-picker
                  v-model="planForm.demandDate"
                  type="date"
                  placeholder="请选择需求日期"
                  value-format="YYYY-MM-DD"
                  class="w-100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单编号">
                <el-input v-model="planForm.orderCode" placeholder="请输入订单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select v-model="planForm.status" placeholder="请选择状态" :disabled="!isEditMode" class="w-100">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="planForm.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件">
                <el-upload
                  class="upload-block"
                  drag
                  action="#"
                  :auto-upload="false"
                  :file-list="attachmentFiles"
                  :before-upload="() => false"
                  @change="handleAttachmentChange"
                  @remove="handleAttachmentRemove"
                >
                  <div class="upload-placeholder">
                    <p>点击或拖拽上传附件</p>
                    <span class="upload-desc">支持 docx、xls、pdf、zip、png、jpg 等格式</span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </section>

        <section class="section-block">
          <div class="section-header space-between">
            <span>BOM组成</span>
            <span class="tips-text">选择成品后自动匹配BOM组合</span>
          </div>
          <el-table v-if="selectedBomDisplay.length" :data="selectedBomDisplay" border stripe class="bom-table">
            <el-table-column type="index" label="序号" width="70" />
            <el-table-column prop="bomcode" label="BOM编号" min-width="160" />
            <el-table-column prop="bomname" label="BOM名称" min-width="200" />
            <el-table-column prop="version" label="版本" width="120" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="danger" link @click="removeBomItem(row.bomid)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="请选择需要关联的BOM" />
        </section>
      </el-form>
    </el-card>

    <!-- 成品选择 -->
    <el-dialog v-model="productDialog.visible" title="选择成品" width="880px">
      <el-form inline class="dialog-filter" @submit.prevent>
        <el-form-item>
          <el-input
            v-model="productDialog.keyword"
            placeholder="请输入产品名称/编号"
            clearable
            @keyup.enter="fetchProductLookup"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchProductLookup">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="productDialog.list"
        border
        height="420"
        v-loading="productDialog.loading"
        @row-click="handleProductRowClick"
        highlight-current-row
      >
        <el-table-column prop="productcard" label="成品编号" min-width="160" />
        <el-table-column prop="productname" label="成品名称" min-width="160" />
        <el-table-column prop="productmodelsame" label="规格型号" min-width="160" />
        <el-table-column prop="productunit" label="单位" width="80" />
      </el-table>
      <template #footer>
        <el-button @click="productDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, EditPen, HomeFilled, Menu, Search, Setting } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules, type UploadUserFile } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface ProductOption {
  id: number
  productcard: string
  productname: string
  productmodelsame: string
  productunit: string
  producttypeid: number
}

interface PlanProductBom {
  bomid: number
  bomcode: string
  bomname: string
  version: string
}

interface PlanForm {
  planCode: string
  planName: string
  workOrderCount: number
  sourceType: number
  orderCode: string
  productId: string
  productName: string
  productmodelsame: string
  productunit: string
  producttypeid?: number
  planCount: number
  planStartTime: string
  planEndTime: string
  demandDate: string
  status: number
  remark: string
  attachment: string
  bomIds: number[]
}

const router = useRouter()
const route = useRoute()
const planId = ref<number | null>(null)
const planFormRef = ref<FormInstance>()

const planForm = reactive<PlanForm>({
  planCode: '',
  planName: '',
  workOrderCount: 0,
  sourceType: 1,
  orderCode: '',
  productId: '',
  productName: '',
  productmodelsame: '',
  productunit: '',
  producttypeid: undefined,
  planCount: 0,
  planStartTime: '',
  planEndTime: '',
  demandDate: '',
  status: 1,
  remark: '',
  attachment: '',
  bomIds: []
})

const planFormRules: FormRules<PlanForm> = {
  planCode: [{ required: true, message: '请输入计划编号', trigger: 'blur' }],
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  sourceType: [{ required: true, message: '请选择来源类型', trigger: 'change' }],
  productName: [{ required: true, message: '请选择成品名称', trigger: 'change' }],
  planCount: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  planStartTime: [{ required: true, message: '请选择开工日期', trigger: 'change' }],
  planEndTime: [{ required: true, message: '请选择完工日期', trigger: 'change' }],
  demandDate: [{ required: true, message: '请选择需求日期', trigger: 'change' }]
}

const formState = reactive({
  loading: false,
  submitting: false,
  autoCode: true,
  pageTitle: '新增计划'
})

const isEditMode = computed(() => planId.value !== null)
const attachmentFiles = ref<UploadUserFile[]>([])
const productDialog = reactive({
  visible: false,
  keyword: '',
  loading: false,
  list: [] as ProductOption[],
  selection: null as ProductOption | null
})

const productBomList = ref<PlanProductBom[]>([])

const sourceTypeOptions = [
  { label: '销售订单', value: 1 },
  { label: '库存备货', value: 2 },
  { label: '其他', value: 3 }
]
const statusOptions = [
  { label: '未分解', value: 1 },
  { label: '已分解', value: 2 },
  { label: '已完成', value: 3 },
  { label: '已关闭', value: 4 },
  { label: '已撤回', value: 5 }
]

const selectedBomDisplay = computed(() => {
  if (!planForm.bomIds.length) {
    return productBomList.value
  }
  const map = new Map(productBomList.value.map(item => [item.bomid, item]))
  return planForm.bomIds
    .map(id => map.get(id) || ({ bomid: id, bomcode: '-', bomname: '-', version: '-' } as PlanProductBom))
    .filter(Boolean)
})

const resetForm = () => {
  planForm.planCode = ''
  planForm.planName = ''
  planForm.workOrderCount = 0
  planForm.sourceType = 1
  planForm.orderCode = ''
  planForm.productId = ''
  planForm.productName = ''
  planForm.productmodelsame = ''
  planForm.productunit = ''
  planForm.producttypeid = undefined
  planForm.planCount = 0
  planForm.planStartTime = ''
  planForm.planEndTime = ''
  planForm.demandDate = ''
  planForm.status = 1
  planForm.remark = ''
  planForm.attachment = ''
  planForm.bomIds = []
  attachmentFiles.value = []
  productBomList.value = []
}

const buildAutoCode = () => {
  const now = new Date()
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `PLAN${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(
    now.getMinutes()
  )}${pad(now.getSeconds())}`
}

const handleAutoCodeChange = (checked: boolean) => {
  if (checked && !isEditMode.value) {
    planForm.planCode = buildAutoCode()
  }
}

const openProductSelector = () => {
  productDialog.visible = true
  productDialog.keyword = ''
  productDialog.selection = null
  productDialog.list = []
  fetchProductLookup()
}

const fetchProductLookup = async () => {
  productDialog.loading = true
  try {
    const response = await https.Reads.get('/AProduction_Plan/GetPlanProducts', {
      params: { keyword: productDialog.keyword || undefined }
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取产品列表失败'))
    }
    productDialog.list = payload?.data ?? payload?.Data ?? []
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取产品列表失败'))
  } finally {
    productDialog.loading = false
  }
}

const handleProductRowClick = (row: ProductOption) => {
  productDialog.selection = row
}

const confirmProductSelection = () => {
  if (!productDialog.selection) {
    ElMessage.warning('请选择成品')
    return
  }
  const product = productDialog.selection
  planForm.productName = product.productname
  planForm.productId = product.productcard
  planForm.productmodelsame = product.productmodelsame
  planForm.productunit = product.productunit
  planForm.producttypeid = product.producttypeid
  planForm.bomIds = []
  productBomList.value = []
  productDialog.visible = false
  fetchProductBomOptions()
}

const fetchProductBomOptions = async () => {
  if (!planForm.productName) {
    productBomList.value = []
    planForm.bomIds = []
    return
  }
  try {
    const response = await https.Reads.get('/AProduction_Plan/GetProductBoms', {
      params: { productName: planForm.productName }
    })
    const payload = extractPayload(response)
    const list = payload?.data ?? payload?.Data ?? []
    productBomList.value = list
    planForm.bomIds = list.map(item => item.bomid)
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取BOM组合失败'))
  }
}

const removeBomItem = (bomid: number) => {
  planForm.bomIds = planForm.bomIds.filter(item => item !== bomid)
}

const resolveAttachmentFiles = (value?: string) => {
  if (!value) return []
  try {
    const parsed = JSON.parse(value)
    if (Array.isArray(parsed)) {
      return parsed.map((item: any, index: number) => ({
        name: item.name || `附件${index + 1}`,
        url: item.url,
        status: 'success' as const,
        uid: Number(item.uid ?? index)
      })) as UploadUserFile[]
    }
  } catch {
    return []
  }
  return []
}

const syncAttachmentValue = (files: UploadUserFile[]) => {
  const payload = files.map(file => ({
    name: file.name,
    url: file.url,
    uid: Number(file.uid ?? Date.now()),
    size: file.size
  }))
  planForm.attachment = JSON.stringify(payload)
}

const handleAttachmentChange = (_file: UploadUserFile, files: UploadUserFile[]) => {
  attachmentFiles.value = files
  syncAttachmentValue(files)
}

const handleAttachmentRemove = (_file: UploadUserFile, files: UploadUserFile[]) => {
  attachmentFiles.value = files
  syncAttachmentValue(files)
}

const buildSubmitPayload = () => ({
  id: planId.value ?? undefined,
  planCode: planForm.planCode.trim(),
  planName: planForm.planName.trim(),
  workOrderCount: planForm.workOrderCount || 0,
  sourceType: planForm.sourceType,
  orderCode: Number(planForm.orderCode) || 0,
  productId: planForm.productId,
  productName: planForm.productName,
  productmodelsame: planForm.productmodelsame,
  productunit: planForm.productunit,
  producttypeid: planForm.producttypeid ?? 0,
  planCount: Number(planForm.planCount) || 0,
  planStartTime: planForm.planStartTime,
  planEndTime: planForm.planEndTime,
  demandDate: planForm.demandDate,
  status: isEditMode.value ? planForm.status : 1,
  remark: planForm.remark,
  attachment: planForm.attachment,
  bomIds: planForm.bomIds
})

const handleSubmit = async () => {
  if (!planFormRef.value) return
  await planFormRef.value.validate()
  formState.submitting = true
  try {
    const payload = buildSubmitPayload()
    const url = isEditMode.value ? '/Aproduction_planB/Edit' : '/Aproduction_planB/Create'
    const response = await https.Writes.post(url, payload)
    const result = extractPayload(response)
    if (!isRequestSuccess(result)) {
      throw new Error(getResponseMessage(result, isEditMode.value ? '编辑失败' : '新增失败'))
    }
    ElMessage.success(getResponseMessage(result, isEditMode.value ? '编辑成功' : '新增成功'))
    router.push('/AProduction_PlanView')
  } catch (error) {
    ElMessage.error(getErrorMessage(error, isEditMode.value ? '编辑失败' : '新增失败'))
  } finally {
    formState.submitting = false
  }
}

const handleCancel = () => {
  router.back()
}

const loadPlanDetail = async (id: number) => {
  formState.loading = true
  try {
    const response = await https.Reads.get('/AProduction_Plan/GetPlanDetail', { params: { id } })
    const payload = extractPayload(response)
    const detail = payload?.data ?? payload?.Data
    if (!detail) {
      throw new Error(getResponseMessage(payload, '获取生产计划详情失败'))
    }

    planForm.planCode = detail.planCode
    planForm.planName = detail.planName
    planForm.workOrderCount = detail.workOrderCount ?? 0
    planForm.sourceType = detail.sourceType
    planForm.orderCode = String(detail.orderCode ?? '')
    planForm.productId = detail.productId
    planForm.productName = detail.productName
    planForm.productmodelsame = detail.productmodelsame
    planForm.productunit = detail.productunit
    planForm.producttypeid = detail.producttypeid
    planForm.planCount = detail.planCount
    planForm.planStartTime = detail.planStartTime
    planForm.planEndTime = detail.planEndTime
    planForm.demandDate = detail.demandDate
    planForm.status = detail.status
    planForm.remark = detail.remark ?? ''
    planForm.attachment = detail.attachment ?? ''
    planForm.bomIds = detail.bomIds ?? []
    productBomList.value = detail.bomItems ?? []
    attachmentFiles.value = resolveAttachmentFiles(planForm.attachment)
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取生产计划详情失败'))
    router.push('/AProduction_PlanView')
  } finally {
    formState.loading = false
  }
}

onMounted(() => {
  const idParam = route.query.id
  if (idParam) {
    planId.value = Number(idParam)
    formState.autoCode = false
    formState.pageTitle = '编辑计划'
    loadPlanDetail(planId.value)
  } else {
    resetForm()
    planForm.planCode = buildAutoCode()
  }
})
</script>

<style scoped>
.plan-add-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.form-header h2 {
  margin: 0;
  font-size: 20px;
}

.form-header p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 13px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.plan-form {
  background: rgba(248, 249, 253, 0.9);
  padding: 16px;
  border-radius: 12px;
}

.section-block {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px rgba(31, 45, 61, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 16px;
}

.section-header.space-between {
  justify-content: space-between;
}

.tips-text {
  font-size: 13px;
  color: #909399;
}

.code-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}

.w-100 {
  width: 100%;
}

.upload-block {
  width: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.upload-desc {
  font-size: 12px;
}

.bom-table {
  margin-top: 12px;
}

.clickable-icon {
  cursor: pointer;
}

.dialog-filter {
  margin-bottom: 12px;
}
</style>

